<?php
/**
 * My new Zend Framework project
 * 
 * @author  
 * @version 
 */

require_once 'Zend/Controller/Plugin/Abstract.php';
require_once 'Zend/Controller/Front.php';
require_once 'Zend/Controller/Request/Abstract.php';
require_once 'Zend/Controller/Action/HelperBroker.php';
/**
 * 
 * Initializes configuration depndeing on the type of environment 
 * (test, development, production, etc.)
 *  
 * This can be used to configure environment variables, databases, 
 * layouts, routers, helpers and more
 *   
 */
class Initializer extends Zend_Controller_Plugin_Abstract
{
    /**
     * @var Zend_Config
     */
    protected static $_config;

    protected static $_iConfig;

    /**
     * @var string Current environment
     */
    protected $_env;

    /**
     * @var Zend_Controller_Front
     */
    protected $_front;

    /**
     * @var string Path to application root
     */
    protected $_root;

    /**
     * Constructor
     *
     * Initialize environment, root path, and configuration.
     * 
     * @param  string $env 
     * @param  string|null $root 
     * @return void
     */
    public function __construct($env, $root = null)
    {
        $this->_setEnv($env);
        if (null === $root) {
            $root = realpath(dirname(__FILE__) . '/../');
        }
        $this->_root = $root;

        Zend_Registry::set("documentRoot",$root);

        $this->initPhpConfig();
        
        $this->_front = Zend_Controller_Front::getInstance();
        //read config
        $this->_config = new Zend_Config_Xml ($this->_root . '/conf/config.xml', 'production' );

        Zend_Registry::set ('config', $this->_config);

        $this->_iConfig = new Zend_Config_Xml ($this->_root . '/application/initializer.xml', 'production' );
        
        // set the test environment parameters
        if ($env == '../test') {
			// Enable all errors so we'll know when something goes wrong. 
			error_reporting(E_ALL | E_STRICT);  
			ini_set('display_startup_errors', 1);  
			ini_set('display_errors', 1); 

			$this->_front->throwExceptions(true);
        }
    }

    /**
     * Initialize environment
     * 
     * @param  string $env 
     * @return void
     */
    protected function _setEnv($env) 
    {
		$this->_env = $env;    	
    }
    

    /**
     * Initialize Data bases
     * 
     * @return void
     */
    public function initPhpConfig()
    {
    	
    }
    
    /**
     * Route startup
     * 
     * @return void
     */
    public function routeStartup(Zend_Controller_Request_Abstract $request)
    {
    		try{
		       	$this->initDb();
		        $this->initHelpers();
		        $this->initView();
		        $this->initPlugins();
		        $this->initRoutes();
		        $this->initControllers();
		        $this->initModules();
		        $this->initLocale();
		        $this->initVersion();
		        $this->initGiftImagePath();    			
		        $this->initTempFolderPath();
		        $this->initPrivateImageDomainPath();
		        $this->initSendEmailConstant();
		        $this->initSshPicConstant();
    		}catch(Exception $e){
    			echo $e->getMessage();
    		}
    }
    
    /**
     * Initialize data bases
     * 
     * @return void
     */
    public function initDb()
    {
        $db_prefix = $this->_config->database->dbprefix;
        $master_params = $this->_config->database->master->params->toArray ();
        $slave_params = $this->_config->database->slave->params->toArray ();
        $master_params['dbname'] = $db_prefix . "_" . $master_params['dbname'];
        $slave_params['dbname'] = $db_prefix . "_" . $slave_params['dbname'];
    	$db_w = Zend_Db::factory ( $this->_config->database->adapter, $master_params );
        $db_r = Zend_Db::factory ( $this->_config->database->adapter, $slave_params);
        $db_w->query("SET NAMES utf8; ");
        $db_r->query("SET NAMES utf8; ");
        Zend_Db_Table::setDefaultAdapter($db_w);
        Zend_Registry::set("db_w", $db_w);
        Zend_Registry::set("db_r", $db_r);
        $db_table_prefix = "";
        Zend_Registry::set("db_table_prefix", $db_table_prefix);
    }

    /**
     * Initialize action helpers
     * 
     * @return void
     */
    public function initHelpers()
    {
    	// register the default action helpers
    	//Zend_Controller_Action_HelperBroker::addPath('../application/default/helpers', 'Zend_Controller_Action_Helper');
    }
    
    /**
     * Initialize view 
     * 
     * @return void
     */
    public function initView()
    {
		// Bootstrap layouts
		Zend_Layout::startMvc(array(
		    'layoutPath' => $this->_root .  '/application/default/layouts',
		    'layout' => 'main'
		));
    	
    }
    
    /**
     * Initialize plugins 
     * 
     * @return void
     */
    public function initPlugins()
    {
    	
    }
    
    /**
     * Initialize routes
     * 
     * @return void
     */
    public function initRoutes()
    {
//    	$route = new Zend_Controller_Router_Route(
//    				'author/:username',
//    				array('controller' => 'user',
//        				'action'=> 'index','username'=>'jiangyiju')
//		);
//		$router=$this->_front->getRouter();
//		$router->addRoute('news',$route);
//    	$this->_front->setRouter($router);
    }

    /**
     * Initialize Controller paths 
     * 
     * @return void
     */
    public function initControllers()
    {
    	$this->_front->setControllerDirectory(array(
                    'default' => $this->_root . '/application/default/controllers',
                    'acl'=> $this->_root . '/application/admin/acl/controllers',
                    'department'=> $this->_root . '/application/admin/department/controllers',
                    'inventory'=> $this->_root . '/application/inventory/controllers',
                    'customer'=> $this->_root . '/application/customer/controllers',
                    'config' => $this->_root . '/application/admin/config/controllers',
                    'order' => $this->_root . '/application/order/controllers',
                    'cms' => $this->_root . '/application/cms/controllers',
                    'promotion' => $this->_root . '/application/promotion/controllers',
                    'metadata' => $this->_root . '/application/metadata/controllers',
                    'consult' => $this->_root . '/application/consult/controllers',
    	            'trade' => $this->_root . '/application/trade/controllers',
    	            'gift' => $this->_root . '/application/gift/controllers',
    	            'systemlog' => $this->_root . '/application/systemlog/controllers'
    		)
	);
    }

    public function initModules(){
        $modules = $this->_iConfig->modules->toArray ();
        Zend_Registry::set ( 'modules', $modules );
    }

    public function initLocale(){
        $country = $this->_config->country;
        $language = $this->_config->language;
        Zend_Registry::set ( 'country', $country );
        Zend_Registry::set ( 'language', $language );
        Zend_Registry::set ( 'lan_cou', $language . "_" . $country );
    }

    public function initVersion(){
        //$version = $this->_config->version;
        //Zend_Registry::set ( 'version', $version );
    }
    
    public function initGiftImagePath(){
    	$giftImagePath = $this->_config->giftimagepath;
    	Zend_Registry::set('gift_image_path',$giftImagePath);
    }
    
    //初始化上传图片所在的绝对路径
    public function initTempFolderPath(){
    	$tempFolder = $this->_config->tempfolder;
    	Zend_Registry::set('temp_folder', $tempFolder);
    }
    
    //初始化以域名方式访问私有图片路径
    public function initPrivateImageDomainPath(){
    	$domain = $this->_config->domain;
    	$path = "//pi.".$domain."/p";
    	Zend_Registry::set('private_image_domain_path', $path);
    }
    
    //初始化发邮件常量
    public function initSendEmailConstant(){
    	$email_params = $this->_config->sendemail->toArray();
    	Zend_Registry::set("email_params", $email_params);
    }
    
    // 初始化SSH图片处理常量
    public function initSshPicConstant(){
        $ssh_impl = $this->_config->ssh_impl->toArray();
        Zend_Registry::set("ssh_impl", $ssh_impl);
    }
    
}
?>
